package com.example.starter.qrbar.barcode;

import cn.hutool.core.util.ObjUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 王令
 * @since 2023/11/24 10:24
 */
@Slf4j
public class ThreadBarcode extends ThreadLocal<Barcode> {

    // 设置编码格式
    private static final Map<EncodeHintType, Object> hints = new HashMap<>();

    static {
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    }

    @Override
    protected Barcode initialValue() {
        return new Barcode();
    }

    public void setMatrix(MultiFormatWriter multiFormatWriter, String text) throws WriterException {
        get().setMatrix(multiFormatWriter.encode(text, BarcodeFormat.CODE_128, getWidth(), getHeight(), hints));
    }

    public BitMatrix getMatrix() {
        return get().getMatrix();
    }

    public void setWidth(int width) {
        get().setWidth(width);
    }

    public int getWidth() {
        return get().getWidth();
    }

    public void setHeight(int height) {
        get().setHeight(height);
    }

    public int getHeight() {
        return get().getHeight();
    }

    public boolean initialized() {
        return ObjUtil.isNotNull(getMatrix());
    }
}
